package com.story.web.shiro.matcher;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

public class AdminCredentialsMatcher extends HashedCredentialsMatcher {
	private Cache<String, AtomicInteger> passwordRetryCache;
	public AdminCredentialsMatcher(CacheManager cacheManager){
		passwordRetryCache = cacheManager.getCache("adminCache");
	}
	@Override
	public boolean doCredentialsMatch(AuthenticationToken token,
			AuthenticationInfo info) {
		// 对密码进行校验		
		String username = (String) token.getPrincipal();
		AtomicInteger retryCount = passwordRetryCache.get(username);
		if(retryCount == null){
			retryCount = new AtomicInteger(0);
			passwordRetryCache.put(username, retryCount);
		}
		if(retryCount.incrementAndGet()>5){
			throw new ExcessiveAttemptsException("密码重试次数太多了！！！");
		}
		boolean mathes = super.doCredentialsMatch(token, info);
		if(mathes){
			//如果输入密码正确，则清空缓存
			passwordRetryCache.remove(username);
		}
		return mathes;
	}
	
	
}
